from Captcha.Visual.Tests import PseudoGimpy           
from django.forms import Widget, Field, ValidationError
from django.utils.translation import ugettext_lazy as _   
from django.core.urlresolvers import reverse 
import variables


class CaptchaWidget(Widget):
    """widget for displaying captcha image field and a code field"""  

    def render(self, name, value, attrs=None):           
        return u'''<img src="%(imageurl)s" alt="" />
            <br/><input type="text" name="%(name)s" id="id_%(name)s" />''' %  {'name':name, 'imageurl': reverse("captcha-image")}

class CaptchaField(Field):                      
    """
    Field definition for a captcha
    Add to your form to do 'human tests'
    """
    
    default_error_messages = {
        'wrong_code': _(u'Wrong code entered'),
        'cookie_not_set': _(u'Cookie is not set. Turn on cookies in your browser'),
    }                 
    
    widget = CaptchaWidget         
    required = True
    
    def __init__(self, *args, **kwargs):
        assert variables.middleware_enabled , "The captcha module requires captcha middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'captcha.middleware.CaptchaMiddleware'."        
        super(CaptchaField, self).__init__(*args, **kwargs)
          
    def clean(self, value):                
        """Validate captcha"""
        
        super(CaptchaField, self).clean(value)
                
        if variables.code is None:      #Cookies is not set	
            raise ValidationError(self.error_messages['cookie_not_set'])
        elif variables.code != hash(value):         #Wrong code was entered	
            variables.code = None
            raise ValidationError(self.error_messages['wrong_code'])
            